#include "ThinkGearDevice.h"



ThinkGearDevice::ThinkGearDevice(IODeviceContext* context)
	: IODeviceWithThreadSupport(IO_DEVICE_THINKGEAR, context)
{
}

ThinkGearDevice::~ThinkGearDevice()
{
}

int ThinkGearDevice::Init()
{
	m_hDllVersion = TG_GetDriverVersion();
	m_hConnectID = TG_GetNewConnectionId();

	int baudrate = m_Context->GetThinkGearBaudRate();

	int errCode = TG_Connect(m_hConnectID,
		m_Context->GetThinkGearPort().c_str(),
		baudrate,
		TG_STREAM_PACKETS);

	SendOperation(IO_OPERATION_THINKGEAR_GET_ATTENTION_VALUE, 0);
	Start();
	return true;
}

int ThinkGearDevice::DeInit()
{
	Stop();
	TG_FreeConnection(m_hConnectID);
	return true;
}

int ThinkGearDevice::ReadData()
{
	static float value = 0;
	int errCode = TG_ReadPackets(m_hConnectID, 1);
	if (errCode == 1) {
		if (TG_GetValueStatus(m_hConnectID, TG_DATA_ATTENTION) != 0) {
			value = TG_GetValue(m_hConnectID, TG_DATA_ATTENTION);
			Notice(GetType(), IO_OPERATION_THINKGEAR_GET_ATTENTION_VALUE, reinterpret_cast<unsigned int>(&value));
		}
	}
	return 0;
}

void ThinkGearDevice::OnOperation(IODeviceOperation operation, unsigned int param)
{
	if (operation == IO_OPERATION_THINKGEAR_GET_ATTENTION_VALUE) {
		ReadData();
		SendOperation(IO_OPERATION_THINKGEAR_GET_ATTENTION_VALUE, 0);
	}
}